#include<hikari.h>
#include "RandomFileAccess.h"


RandomFileAccess::RandomFileAccess(const char*path){
	this->path=path;
}


RandomFileAccess::~RandomFileAccess(void){
	if(file!=NULL){
		fclose(file);
		file=NULL;
	}
}

bool RandomFileAccess::openFileWorReading(){
	fopen_s(&file, path.c_str(), "rb");
	if(file){
		return true;
	}else{
		return false;
	}
}

bool RandomFileAccess::readBool(){
	char val=0;
	fread(&val, sizeof(val), 1, file);
	return val==1;
}

unsigned short RandomFileAccess::readShort(){
	unsigned short val=0;
	fread(&val, sizeof(val), 1, file);
	unsigned short v1=val>>8;
	val=val<<8;
	val|=v1;
	return val;
}

float RandomFileAccess::readFloat(){
	unsigned int ui=0;
	fread(&ui, sizeof(ui), 1, file);
	ui = (ui >> 24) |
		((ui<<8) & 0x00FF0000) |
		((ui>>8) & 0x0000FF00) |
		(ui << 24);
	float val=*((float*)&ui);
	return val;
}

unsigned char RandomFileAccess::readByte(){
	unsigned char val=0;
	fread(&val, sizeof(val), 1, file);
	return val;
}

wchar_t RandomFileAccess::readChar(){
	wchar_t val=readShort();
	return val;
}

int RandomFileAccess::readInt(){
	unsigned int ui=0;
	fread(&ui, sizeof(ui), 1, file);
	ui = (ui >> 24) |
		((ui<<8) & 0x00FF0000) |
		((ui>>8) & 0x0000FF00) |
		(ui << 24);

	return ui;
}

long long RandomFileAccess::readLong(){
	long long a=0;
	fread(&a, sizeof(a), 1, file);
	a = ((a & 0x00000000000000FFULL) << 56) | 
		((a & 0x000000000000FF00ULL) << 40) | 
		((a & 0x0000000000FF0000ULL) << 24) | 
		((a & 0x00000000FF000000ULL) <<  8) | 
		((a & 0x000000FF00000000ULL) >>  8) | 
		((a & 0x0000FF0000000000ULL) >> 24) | 
		((a & 0x00FF000000000000ULL) >> 40) | 
		((a & 0xFF00000000000000ULL) >> 56);
	return a;
}

wstring RandomFileAccess::readString(){
	int bytesCount=readShort();
	char*bytes=new char[bytesCount+2];
	fread(bytes, sizeof(char), bytesCount, file);
	//bytes[bytesCount+1]=0;
	bytes[bytesCount]=0;
	int stringSize=u8_strlen(bytes);
	wchar_t*resultString=new wchar_t[stringSize+1];
	u8_toucs(resultString, stringSize+1, bytes, bytesCount);
	delete [] bytes;
	bytes=NULL;
	std::wstring string=resultString;
	delete[]resultString;
	resultString=NULL;
	return string;
}

int RandomFileAccess::seek(unsigned long position){
	fseek(file, position, SEEK_SET);
	return 0;
}

void RandomFileAccess::close(){
	if(file!=NULL){
		fclose(file);
		file=NULL;
	}
}